package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Peachblossom;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@DubboService
public class PeachblossomApiImpl implements PeachblossomApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    //修改次数
    @Override
    public int updateRemainingTimes(Long id) {
        Query query = Query.query(Criteria.where("userId").is(id));
            //修改
            FindAndModifyOptions options = new FindAndModifyOptions();
            options.returnNew(true);
            Update update = new Update();
            update.inc("remainingTimes", -1);
            Peachblossom andModify = mongoTemplate.findAndModify(query, update, options, Peachblossom.class);
        return andModify.getRemainingTimes();
    }
    //修改全部剩余次数
    @Override
    public void updateRemainingTimes(Integer num) {
        Query query = Query.query(Criteria.where("remainingTimes").ne(10));
        //修改
        Update update = new Update();
        update.set("remainingTimes", num);
        mongoTemplate.updateMulti(query, update, Peachblossom.class);
    }

    //查询
    @Override
    public Peachblossom findByUserId(Long id) {
        Query query = Query.query(Criteria.where("userId").is(id));
        Peachblossom peachblossom = mongoTemplate.findOne(query, Peachblossom.class);
        if (peachblossom == null) {
            //保存
            peachblossom = new Peachblossom();
            peachblossom.setUserId(id);
            peachblossom.setCreated(System.currentTimeMillis());
            mongoTemplate.save(peachblossom);
       }
        return peachblossom;
    }
}
